$(function () {
    let carList,
        delArr = [],
        tipstr,
        free = 199, /* 包邮价格 */
        htmlStr = '';
    var userName = [];
    userName = JSON.parse(localStorage.getItem('username'))
    if (userName == null || userName.length == 0) {
        userName = []
    } else {
        $('.header-r').html(`
            <span class="uname">${userName[userName.length - 1].uname}，您好</span> <span>|</span>
            <a class="esclogin">退出</a>
        `)
        $('.empty-cart-top').html(`
                    <h2 class="login-tip is-login">${userName[userName.length - 1].uname},您的购物车还是空的！</h2>
                    <a href="http://localhost/mi/list/list.html" class="btn-primary">马上去购物</a>
        `)
        $('.esclogin').click(() => {
            localStorage.removeItem('username')
            location.reload()
        })
    }





    var detailList
    if (detailList == null || detailList.length == 0) {
        detailList = []
    }
    const tbody = document.querySelector('table');

    let goods = document.querySelector('.cart-recommend');
    goods.addEventListener('click', event => {
        if (event.target.className == 'in') {
            let join = event.target.parentElement
            console.log(join);
            var goodObj = {
                id: $(join).parent().find('.p4').text(),
                imgurl: $(join).parent().find('img')[0].src,
                name: $(join).parent().find('.p1').html(),
                describe: $(join).parent().find('.p2').html(),
                price: parseInt($(join).parent().find('.p3').html()),
                num: 1
            };

            if (carList.length === 0) {
                // 添加到carList
                carList.push(goodObj);
            } else {
                for (var i = 0; i < carList.length; i++) {
                    // 如果商品已经存在localStorage中，则数量+1
                    if (carList[i].id === goodObj.id) {
                        carList[i].num++;
                        localStorage.setItem('carlist', JSON.stringify(carList))
                        cartIsNull();
                        break
                    }
                } if (i === carList.length) {
                    // 添加到carList
                    carList.push(goodObj);
                    localStorage.setItem('carlist', JSON.stringify(carList))
                    var tr = document.createElement('tr')
                    tr.innerHTML = `
                                        <td class="col-check"><input class="goods-check" type="checkbox"></td>
                                        <td class="col-img">
                                            <a class="goods-det" href="http://localhost/mi/detail/">
                                                <img src="${goodObj.imgurl}" width="80" height="80" alt="">
                                                <p class="data-name" style="display:none">${goodObj.name}</p>
                                                <p class="data-price" style="display:none">${goodObj.price}起</p>
                                                <span class="data-id" style="display:none">${goodObj.id}</span>
                                                <span class="data-describe" style="display:none">${goodObj.describe}</span>
                                            </a>
                                        </td>
                                        <td class="col-name">
                                            <h3>${goodObj.name}</h3>
                                        </td>
                                        <td class="col-price">${goodObj.price}元</td>
                                        <td class="col-num">
                                            <div>
                                            <a href="javascript:;" class="reduce iconfont">&#xeca3;</a>
                                            <input type="text" class="amount" value=${goodObj.num} size=5 maxlength="5" min=0 max=100>
                                            <a href="javascript:;" class="add iconfont">&#xe635;</a>
                                            </div>
                                        </td>
                                        <td class="col-total"><span>${parseInt(goodObj.price) * parseInt(goodObj.num)}元</span></td>
                                        <td><a href="javascript:;" class="del iconfont"><span class="goods-id" style="display:none">${goodObj.id}</span>&#xe61e;</a></td>
                                  `
                    tbody.appendChild(tr);
                    updataAmount();
                    updataTotal();
                }
            }
            localStorage.setItem('carlist', JSON.stringify(carList))
            if (carList.length === 1) {
                cartIsNull();
                $('.checkAll').prop("checked", false)
            }
        }
    })
    cartIsNull();

    //渲染table表格函数
    function show() {
        htmlStr = ''
        carList = JSON.parse(localStorage.getItem('carlist'))
        Array.from(carList).forEach((item, index) => {
            htmlStr += ` <tr>
                    <td class="col-check"><input class="goods-check" type="checkbox"></td>
                    <td class="col-img">
                        <a class="goods-det" href="http://localhost/mi/detail/">
                            <img src="${item.imgurl}" width="80" height="80" alt="">
                            <p class="data-name" style="display:none">${item.name}</p>
                            <p class="data-price" style="display:none">${item.price}起</p>
                            <span class="data-id" style="display:none">${item.id}</span>
                            <span class="data-describe" style="display:none">${item.describe}</span>
                        </a>
                    </td>
                    <td class="col-name">
                        <h3>${item.name}</h3>
                    </td>
                    <td class="col-price">${item.price}元</td>
                    <td class="col-num">
                        <div>
                            <a href="javascript:;" class="reduce iconfont">&#xeca3;</a>
                            <input type="text" class="amount" value=${item.num} size=5 maxlength="5" min=0 max=100>
                            <a href="javascript:;" class="add iconfont">&#xe635;</a>
                        </div>
                    </td>
                    <td class="col-total"><span>${parseInt(item.price) * parseInt(item.num)}元</span></td>
                    <td><a href="javascript:;" class="del iconfont"><span class="goods-id" style="display:none">${item.id}</span>&#xe61e;</a></td>
                </tr>`

        });
        tbody.innerHTML = htmlStr;

    }
    //当购物车商品发生改变时调用该函数
    function cartIsNull() {
        carList = JSON.parse(localStorage.getItem('carlist'))
        if (carList == null || carList.length == 0) {
            carList = []
            htmlStr = ''
            $('.wrap>.main>.cart-top').css('display', 'none');
            $('.empty-cart-top').css('display', 'block')
            $('.cart-recommend>h2>span').html('为您推荐')
        } else {
            $('.wrap>.main>.cart-top').css('display', 'block');
            $('.empty-cart-top').css('display', 'none')
            show()
            updataAmount();
            updataTotal();
            detail()

        }
    }
    //购物车基础功能实现   
    $('.cart-list').on('click', '.checkAll , .goods-check , .add , .reduce , .del', function (event) {
        switch (event.target.className) {
            // 数量加时
            case "add iconfont":
                $(this).prev().val(function (index, val) {
                    return val - 0 + 1;
                })
                var val = $(this).prev().val(),
                    amount = $(this).parent().parent().prev().html(),
                    subtotal = parseInt(val) * parseInt(amount),
                    goodsId = $(this).parent().parent().parent().find('.goods-id').html()
                $(this).parent().parent().next().find('span').html(subtotal + '元')
                for (let i = 0; i < carList.length; i++) {
                    if (carList[i].id === goodsId) {
                        carList[i].num++;
                        localStorage.setItem('carlist', JSON.stringify(carList))
                    }
                }
                // $(event.target).prev()[0].value = parseInt($(event.target).prev()[0].value) + 1
                // $(event.target).parent().parent().next().find('span')[0].innerText = (parseInt($(event.target).parent().find('input').val()) * parseInt($(event.target).parent().parent().prev().text())) + '元'
                break;
            // 数量减时
            case "reduce iconfont":
                $(this).next().val(function (index, val) {
                    return --val < 0 ? 0 : val;
                })
                var val = $(this).next().val(),
                    amount = $(this).parent().parent().prev().html(),
                    subtotal = parseInt(val) * parseInt(amount),
                    goodsId = $(this).parent().parent().parent().find('.goods-id').html()
                console.log(goodsId);
                $(this).parent().parent().next().find('span').html(subtotal + '元')
                for (let i = 0; i < carList.length; i++) {
                    if (carList[i].id === goodsId) {
                        carList[i].num--;
                        localStorage.setItem('carlist', JSON.stringify(carList))
                    }
                }
                // $(event.target).next()[0].value -= 1
                // $(event.target).parent().parent().next().find('span')[0].innerText = (parseInt($(event.target).parent().find('input').val()) * parseInt($(event.target).parent().parent().prev().text())) + '元'
                break;
            // 点击全选时
            case "checkAll":
                let status = $(this).prop("checked")
                $('.checkAll, .goods-check').prop("checked", status)
                break;
            // 商品选中时
            case "goods-check":
                let res = Array.from($('.goods-check')).every(item => {
                    return $(item).prop("checked");
                })
                $(".checkAll").prop("checked", res)
                break;
            // 点击删除商品时
            case "del iconfont":
                $('.mi-popup').fadeIn(500);
                $('.close').click(() => {
                    $('.mi-popup').fadeOut(500)
                });
                $('.btn-gray').click(() => {
                    $('.mi-popup').fadeOut(500)
                });
                //确认删除商品功能
                $('.btn-primary').click(() => {
                    updataAmount();
                    updataTotal();
                    $(this).parent().parent().remove();
                    delArr.push($(this).find('span').text())
                    // 同步后台数据删除
                    for (let i = 0; i < carList.length; i++) {
                        if (carList[i].id == delArr[delArr.length - 1]) {
                            carList.splice(i, 1)
                            localStorage.setItem('carlist', JSON.stringify(carList))
                            i--
                            updataAmount();
                            updataTotal();
                        }
                    }
                    $('.mi-popup').fadeOut(500)
                    if (carList.length == 0) {
                        cartIsNull();
                    }
                })
                break;
            default:
                break;
        }
        updataAmount();
        updataTotal();
    })

    //计算总量
    function updataAmount() {
        // 获取选中项
        const chks = Array.from($('.amount')).filter(item => {
            return $(item).parent().parent().parent().find('.goods-check').prop('checked')
        })
        let total = chks
            .map(item => Number(item.value))
            .reduce((acc, current) => acc + current, 0);
        $('.cart-total').find('i').eq(1).html(total)
        if (total == 0) {
            $('.total').css('background', 'gainsboro').css('border-color', 'gainsboro')
        } else {
            $('.total').css('background', '#ff6700').css('border-color', '#ff6700')
        }
        let totalAll = Array.from($('.amount'))
            .map(item => Number(item.value))
            .reduce((acc, current) => acc + current, 0);
        $('.cart-total').find('i').eq(0).html(totalAll)
        localStorage.setItem('goodsnum', $('.cart-total').find('i').eq(0).html())


    }
    //计算总价

    function updataTotal() {
        // 获取选中项
        const chks = Array.from($('.col-total span')).filter(item => {
            return $(item).parent().parent().find('.goods-check').prop('checked')
        })
        let total = chks
            .map(item => parseInt(item.innerHTML))
            .reduce((acc, current) => acc + current, 0);
        $('.cart-fooder-r span i').html(total)

        //判断总价格是否凑够包邮
        if (total >= free) {
            $('.cart-tips').css('display', 'none')
        } else {
            $('.cart-tips').css('display', 'block')
            tipstr = `
                <div class="tip">小米发货商品（不含有品）满${free}元免运费,还需</div>
                <span>${free - total}<span>元</span></span>
                <a href="http://localhost/mi/list/list.html">去凑单 ></a>
                `
            $('.cart-tips').html(tipstr)
        }
    }

    function detail() {
        $('.goods-det').click(function (event) {
            // event.preventDefault()
            console.log($(this));
            var goodObj = {
                id: $(this).find('.data-id').text(),
                imgurl: $(this).find('img')[0].src,
                name: $(this).find('.data-name').html(),
                describe: $(this).find('.data-describe').html(),
                price: parseInt($(this).find('.data-price').html()),
                num: 1
            };
            // console.log(goodObj.id, goodObj.imgurl, goodObj.name, goodObj.describe, goodObj.price);

            if (detailList.length === 0) {
                // 添加到detailList
                detailList.push(goodObj);
            } else {
                for (var i = 0; i < detailList.length; i++) {
                    // 如果商品已经存在cookie中，则数量+1
                    if (detailList[i].id === goodObj.id) {
                        detailList[i].num++;
                        localStorage.setItem('detaillist', JSON.stringify(detailList))
                        break
                    }
                } if (i === detailList.length) {
                    // 添加到detailList
                    detailList.push(goodObj);
                    localStorage.setItem('detaillist', JSON.stringify(detailList))
                }
            }
            localStorage.setItem('detaillist', JSON.stringify(detailList))
        })
    }
})